package com.dbh.design.proxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author dongbanghui
 * @create 2023/4/9
 */
public class $Proxy0 extends Proxy implements Foo {

    public $Proxy0(InvocationHandler h) {
        super(h);
    }

    private static Method foo;
    private static Method bar;
    static {
        try {
            foo = Foo.class.getMethod("foo");
            bar = Foo.class.getMethod("bar");
        } catch (NoSuchMethodException e) {
            throw new NoSuchMethodError(e.getMessage());
        }
    }

    /**
     * 目标接口方法
     */
    @Override
    public void foo() {
        try {
            h.invoke(this, foo, new Object[0]);
        } catch (RuntimeException | Error e) {
            // 运行时异常直接抛出
            throw e;
        } catch (Throwable e) {
            // 检查异常转成运行时异常抛出
            throw new UndeclaredThrowableException(e);
        }
    }

    /**
     *
     */
    @Override
    public int bar() {
        try {
            Object result = h.invoke(this, bar, new Object[0]);
            return (int)result;
        }  catch (RuntimeException | Error e) {
            // 运行时异常直接抛出
            throw e;
        } catch (Throwable e) {
            // 检查异常转成运行时异常抛出
            throw new UndeclaredThrowableException(e);
        }
    }
}
